package com.rtx.wms.std.handler.cc.mid;

import java.util.Arrays;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.model.emums.SysNumberType;
import com.rtx.wms.std.cc.bean.ApiCcList;
import com.rtx.wms.std.cc.bean.RtxCCProduct;
import com.rtx.wms.std.cc.service.ApiCcListService;
import com.rtx.wms.std.cc.service.RtxCCProductService;
import com.rtx.wms.std.common.bean.WmsConstant;
import com.rtx.wms.std.common.service.CommonService;

import cn.hutool.core.util.StrUtil;

/**
 * 盘点单中间表
 */
@Component
public class MidCClistHandler {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ApiCcListService apiCcListService;
    
    @Autowired
    private CommonService commonService;
    
    @Autowired
    RtxCCProductService rtxCCProductService;


    /**
     * 出库单从中间表写入WMS
     * @param whseid
     */
    public void handlerMidToWms(String whseid){
        //获取中间表未处理成功的订单
        List<ApiCcList> cclist = selectApiData("ris_edi");
        if(CollectionUtils.isEmpty(cclist)){
            return;
        }
        for(ApiCcList o : cclist){
            addWmsOrders(whseid,o);
            //更新中间表状态
            updateApiOrders("ris_edi",o);
        }
    }

    /**
     * 更新中间表
     * @param whseid
     * @param apiOrders
     */
    private void updateApiOrders(String whseid,ApiCcList c) {
        LambdaUpdateWrapper<ApiCcList> update = Wrappers.lambdaUpdate();
        update.eq(ApiCcList::getSerialkey,c.getSerialkey())
                .set(ApiCcList::getEdiflag,c.getEdiflag())
                .set(StringUtils.hasLength(c.getSubkey()),ApiCcList::getSubkey, c.getSubkey())
                .set(StringUtils.hasText(c.getEdimsg()),ApiCcList::getEdimsg,StrUtil.sub(c.getEdimsg(),0,200)) ;
        apiCcListService.updStatus(whseid,update);
    }

    /**
     * 添加wms出库单
     * @param whseid
     * @param apiOrders
     */
    void addWmsOrders(String whseid,ApiCcList c){
        try {
        	RtxCCProduct cclist = convertOrders(c.getWhseid(),c);
        	
        	rtxCCProductService.insert(c.getWhseid(), cclist);
            c.setEdiflag(WmsConstant.SUCCESS_FLAG);
        } catch (Exception e) {
            logger.error("仓库{}，批次号{}从中间表写入WMS异常",whseid,c.getBatchid(),e);
            c.setEdiflag(WmsConstant.FAIL_FLAG);
            c.setEdimsg(e.getMessage());
        }
    }
    
    

    /**
     * 获取中间表未处理成功的订单
     * @param whseid
     * @return
     */
    private List<ApiCcList> selectApiData(String whseid) {
        //获取中间表未处理成功的订单
        LambdaQueryWrapper<ApiCcList> query = Wrappers.lambdaQuery();
        query.in(ApiCcList::getEdiflag, Arrays.asList(WmsConstant.DEFAULT_FLAG,WmsConstant.FAIL_FLAG,WmsConstant.FAIL_FLAG_2))
                .lt(ApiCcList::getRtxqueue,30)
                .last("limit 500");
        return apiCcListService.queryByCondition(whseid, query);
    }

    /**
     * 转化类型
     * @param o
     * @return
     */
    private RtxCCProduct convertOrders(String whseid,ApiCcList c) {
        //获取wms单号
        String subkey = commonService.getWmsKey(whseid, SysNumberType.SYS_NUMBER_TYPE_25);
    	RtxCCProduct cp = new RtxCCProduct();
        BeanUtils.copyProperties(c,cp);
        cp.setTotalkey("");
        cp.setSubkey(subkey);
        cp.setCctype("10");
        cp.setWhseid(c.getWhseid());
        cp.setStorerkey("GREPOW");
        cp.setRtxerptasktype(c.getRtxErptasktype());
        cp.setSkulist(c.getSkulist());
        cp.setIsblind("1");
        cp.setDynamic("D");
        cp.setAddwho("API");
        cp.setEditwho("API");
        c.setSubkey(subkey);
        return cp;
    }
}
